package it.ma.musicplayernew;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.hxjr.dialog.DialogUtils;
import com.hxjr.dialog.SweetAlertDialog;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.zhongdao.swing.R;

import it.ma.musicplayernew.fragment.AllTracks;
import it.ma.musicplayernew.fragment.ControlPanelFragment2;
import it.ma.musicplayernew.helper.HeadSetHelper;
import it.ma.musicplayernew.modle.Track;
import it.ma.musicplayernew.service.CoreService;

public class MainActivity extends SlidingFragmentActivity implements CoreService.StateChangedListener, View.OnClickListener {

    private ServiceConnection mServiceConnection;
    private CoreService mCoreService;

    public AllTracks mAllTracksFragment;
    public ControlPanelFragment2 mMainFragment;

    // menus

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //处理为捕捉异常
        //ExceptionHandler.getInstance().init(this);

        initImageLoader(this);

        initContentView();

        initSlidingMenu();

        bindToService();
        //startService();

        HeadSetHelper instance = HeadSetHelper.getInstance();
        instance.setOnHeadSetListener(new HeadSetHelper.OnHeadSetListener() {
            @Override
            public void onClick(int keyCode) {
                Log.e("OnHeadSetListener", "onClick");
                if(KeyEvent.KEYCODE_MEDIA_NEXT == keyCode){
                    mAllTracksFragment.next(null);
                }else if(KeyEvent.KEYCODE_MEDIA_PLAY == keyCode
                        ||KeyEvent.KEYCODE_MEDIA_PAUSE == keyCode
                        ||KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE == keyCode){
                    mAllTracksFragment.play(null);
                }else if(KeyEvent.KEYCODE_MEDIA_PREVIOUS == keyCode){
                    mAllTracksFragment.previous(null);
                }
            }

            @Override
            public void onDoubleClick(int keyCode) {
                Log.e("OnHeadSetListener", "onDoubleClick");
                mAllTracksFragment.next(null);
            }
        });

        instance.open(this);
    }

    private BroadcastReceiver mediaButtonReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isActionMediaButton = Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction());
            //判断是不是耳机按键事件
            if (!isActionMediaButton) return;
            KeyEvent event = (KeyEvent) intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            //判断有没有耳机按键事件
            if (event == null) return;
            //过滤按下事件
//            boolean isActionUp = (event.getAction() == KeyEvent.ACTION_UP);
//            if (!isActionUp) return;
            //避免在Receiver里做长时间的处理，使得程序在CPU使用率过高的情况下出错，把信息发给handlera处理。
            int keyCode = event.getKeyCode();
            long eventTime = event.getEventTime() - event.getDownTime();//按键按下到松开的时长
            Log.e("MEDIA_BUTTON: " , "keyCode:" + keyCode + " eventTime:" + eventTime);
            //终止广播(不让别的程序收到此广播，免受干扰)
            abortBroadcast();
        }
    };

    public void exitApp() {
//        mCoreService.cancelNoti();
        unbindService(mServiceConnection);
        finish();
        System.exit(0);
    }

    private void initContentView() {
        setContentView(R.layout.content_frame);
        mAllTracksFragment = new AllTracks();
        mMainFragment = new ControlPanelFragment2();

        initPager();
    }

    private void initPager() {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.content_frame, mMainFragment)
                .commit();

        // set the Behind View
        setBehindContentView(R.layout.menu_frame);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.menu_frame, mAllTracksFragment)
                .commit();
    }

    private void initSlidingMenu() {
        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        slidingMenu.setShadowDrawable(R.drawable.shadow);
        slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        slidingMenu.setFadeDegree(0.35f);
    }

    @Override
    protected void onResume() {
        if (mCoreService != null)
            onPlayStateChanged();

        super.onResume();
    }

    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config);
    }

//    void startService() {
//        final Intent intent = new Intent();
//        intent.setClass(MainActivity.this, CoreService.class);
//        startService(intent);
//    }

    void bindToService() {

        mServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName arg0) {

            }

            @Override
            public void onServiceConnected(ComponentName arg0, IBinder iBinder) {
                CoreService.MyBinder myBinder = (CoreService.MyBinder) iBinder;
                mCoreService = myBinder.getService();
                Log.i("nick_music", mCoreService.toString());
                mCoreService.setActivityCallback(MainActivity.this);

                // update0
                mAllTracksFragment.setServiceCallback(mCoreService);
                mMainFragment.setServiceCallback(mCoreService);

                onPlayStateChanged();
            }
        };

        final Intent intent = new Intent();
        intent.setClass(MainActivity.this, CoreService.class);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);

    }

    public CoreService getServiceCallback() {
        return mCoreService;
    }

    @Override
    protected void onDestroy() {
        try {
            unbindService(mServiceConnection);
        } catch (Throwable t) {
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int btnId = v.getId();
        switch (btnId) {

            case R.id.btn_play_local:
                if (mCoreService.getIsPlaying()) {
                    mCoreService.pausePlayer();
                } else {
                    mCoreService.resumePlayer();
                }
                break;

            case R.id.btn_next_local:
                mCoreService.playNextTrack();
                break;

            case R.id.btn_pre_local:
                mCoreService.playPreviousTrack();
                break;

            default:
                break;
        }
    }

    @Override
    public void onPlayStateChanged() {
        Track currentTrack = mCoreService.getCurrentTrack();

        mAllTracksFragment.onPlayUpdate(currentTrack);
        mMainFragment.onPlayUpdate(currentTrack);
    }

    /**
     * 更新背景
     *
     * @param drawable
     */
    public void onBlurReady(Drawable drawable) {

        if (drawable != null) {
            if(mAllTracksFragment != null){
                mAllTracksFragment.onBlurReady(drawable);
            }
        }
    }

    /*@Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getSlidingMenu().isMenuShowing()) {
                showContent();
            } else {
                showExitDialog();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/

    @Override
    public void onBackPressed() {
        if (mMainFragment.onBackPressed()) {
            return;
        }

        if (getSlidingMenu().isMenuShowing()) {
            showContent();
        } else {
            showExitDialog();
        }
    }

    private SweetAlertDialog mExitDialog;

    private void showExitDialog() {
        mExitDialog = DialogUtils.getInstance().createNormDialog(this, getString(R.string.close_spp));
        mExitDialog.setCanceledOnTouchOutside(true);
        mExitDialog.setCancelable(true);
        mExitDialog.setCancelText(getString(R.string.backgroud_running));
        mExitDialog.setConfirmText(getString(R.string.exit));
        mExitDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                mExitDialog.cancel();
                moveTaskToBack(true);
            }
        });
        mExitDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                mExitDialog.cancel();
                exitApp();
            }
        });

        if (!mExitDialog.isShowing()) {
            mExitDialog.show();
        }

    }
}
